package com.snail.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Monica
 * @description
 * @date 2025/7/10 15:19
 */
@Hidden // SpringBoot3.5.0整合knife4j4.5.0，程序正常启动，但是在打开api页面时报错
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        // 只在有 data 的时候，才返回 data 版本的错误响应
        if (e.getData() != null && !e.getData().isEmpty()) {
            return ResultUtils.error(e.getCode(), e.getData(), e.getMessage());
        }
        return ResultUtils.error(e.getCode(), e.getMessage());
    }


    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    @ExceptionHandler(NotLoginException.class)
    public BaseResponse<?> handleNotLoginException(NotLoginException e) {
        return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
    }
}

